<?php
/**
 * 
 * Database class that extends PDO for some awesome functions. 
 * Extra functions for inserting and updating rows
 * @author Ramon
 *
 */
class Database extends PDO {
	// singleton instance
	private static $instance;
	
	/**
	 * Constructs parent PDO
	 */
	public function __construct($DB_TYPE, $DB_HOST, $DB_NAME, $DB_USER, $DB_PASS) {
		parent::__construct($DB_TYPE.':host='.$DB_HOST.';dbname='.$DB_NAME, $DB_USER, $DB_PASS);		
	}
	
	/**
	 * Singleton like function getInstance of current Database object. 
	 * So Object doesnt need to be instanciated everytime. 
	 */
	public static function getInstance() {

		if(!self::$instance) {
			self::$instance = new self(DB_TYPE, DB_HOST, DB_NAME, DB_USER, DB_PASS);
		}		
		return self::$instance;
		
	}
	
	/**
	 * insert
	 * @param string $table A name of table to insert into
	 * @param string $class A class to insert
	 */
	public function insert($table, $class) {
		unset($class->id);
		$class_vars = get_class_vars(get_class($class));
		unset($class_vars['id']);
		unset($class_vars['db']);
		$fieldNames = implode('`, `', array_keys($class_vars));
		$fieldValues = ':' . implode(', :', array_keys($class_vars));
		
		$sth = $this->prepare("INSERT INTO $table (`$fieldNames`) VALUES ($fieldValues)");

		foreach ($class as $key => $value) {
			if($key != "db") {
				$sth->bindValue(":$key", $value);
			}
		}
		if($sth->execute()) {
			return true;
		} else {
			return false;
		};
	}
	
	/**
	 * update
	 * @param string $table A name of table to insert into
	 * @param string $data An associative array
	 * @param string $where the WHERE query part
	 */
	public function update($table, $data) {		
		$fieldDetails = NULL;
		foreach($data as $key=> $value) {
			if($key != "db" && $key != "id") {
				$fieldDetails .= "`$key`=:$key,";
			} else if ($key == "id") {				
				$where = "id = " . $value;
			}
		}
		$fieldDetails = rtrim($fieldDetails, ',');
		$sth = $this->prepare("UPDATE $table SET $fieldDetails WHERE $where");
		
		foreach ($data as $key => $value) {
			if($key != "db" && $key != "id") {
				$sth->bindValue(":$key", $value);
			} 
		}		
		$sth->execute();
		return true;
	}	
}